package com.besmart.workflow.core.service.loader;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.besmart.workflow.core.exception.OperationIndexCreationException;
import com.besmart.workflow.core.model.ConditionNode;
import com.besmart.workflow.core.model.OperationIndex;
import com.besmart.workflow.core.model.OperationNode;
import com.besmart.workflow.core.model.WorkflowPool;
import com.besmart.workflow.core.service.helper.OperationIndexHelper;

@Service
public class WorkflowLoader {

	private OperationNode currentNode;

	@Autowired
	private WorkflowNodeRunner runner;
	@Autowired
	private WorkflowOperationConnector connector;
	@Autowired
	private OperationIndexHelper helper;

	public void load(OperationNode operation) {
		currentNode = operation;
	}

	public void run() {
		runner.execute(currentNode);
	}

	public void proceed(String triggerString,WorkflowPool pool) throws OperationIndexCreationException {
		ConditionNode condition = currentNode
				.getConditionByTrigger(triggerString);
		String nextOperationInfo = condition.getNextOpr();
		OperationIndex index = helper.createInstance(nextOperationInfo);
		OperationNode nextOperation = pool.getOperationWithOperationIndex(index);
		connector.connect(condition, nextOperation);
		currentNode = nextOperation;
	}

	public OperationNode getCurrentOperation() {
		return currentNode;
	}

}

